#include <sys/time.h>
#include <sys/types.h>
#include <unistd.h>

void keyReadFromInput(char* pipname)
{
	int key;
	char buf;
	char* pipeName;
	fd_set rfds;
	struct timeval tv = {1, 0};

	if( pipname != NULL ){
		pipeName=(char *)pipname;
		pipeFd=open(pipeName, O_RDONLY|O_NONBLOCK);
	}else{
		pipeFd=-1;
	}
	
	while(1){
		FD_ZERO(&rfds);
		FD_SET(0, &rfds);

		if( pipeFd != -1 ){
			FD_SET(pipeFd, &rfds);
			maxFd=MAX(maxFd,pipeFd);
		}

		switch( select( maxFd + 1, &rfds, NULL, NULL, &tv ) ){
		case 0:	//Timeout
			continue;

		case -1:
			printf("select error\n");
			continue;
				
		default:
			if( FD_ISSET(0, &rfds) ){
				if( read( 0, &buf, 1 ) == 1 ){
					printf("gui:keyReadFromStdin:[0x%x]\n",buf);
					//TODO:
				}
			}

			if( (pipeFd != -1) && FD_ISSET(pipeFd, &rfds) ){
				if( read( pipeFd, &key, sizeof(key) ) == sizeof(key) ){
					printf("gui:keyReadFromPipe:[0x%x]\n",key);
					if( (key&0xff) == DKEY_RELEASE ) KER_Outer_EventRemBtnUp();
					else KER_Outer_EventRemBtnDown(key);
				}
			}
			break;
		}
	}
	if( pipeFd != -1 ){
	   close( pipeFd );
	}
}